package org.jeecg.modules.basic.businessparam.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.basic.businessparam.entity.WmsBusiniessParamConfig;
import org.jeecg.modules.basic.businessparam.mapper.WmsBusiniessParamConfigMapper;
import org.jeecg.modules.basic.businessparam.service.IWmsBusiniessParamConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 系统业务参数配置
 * @Author: jeecg-boot
 * @Date: 2024-01-17
 * @Version: V1.0
 */
@Service
public class WmsBusiniessParamConfigServiceImpl extends ServiceImpl<WmsBusiniessParamConfigMapper, WmsBusiniessParamConfig> implements IWmsBusiniessParamConfigService {

    @Autowired
    private RedisUtil redisUtil;

    private final static String BUSINIESS_PREFIX = "wms:businiess:param:";

    @Override
    public void flushConfigParam(String code) {
        if (StringUtils.isNotBlank(code)) {
            redisUtil.del(BUSINIESS_PREFIX + code);
        } else {
            List<WmsBusiniessParamConfig> list = this.list();
            if (CollectionUtils.isNotEmpty(list)) {
                list.stream().map(t -> t.getCode()).forEach(t -> {
                    redisUtil.del(BUSINIESS_PREFIX + t);
                });
            }
        }
    }

    @Override
    public void addKey(String code, String val) {
        redisUtil.set(BUSINIESS_PREFIX + code, val);
    }

    @Override
    public String getBussinessValByCode(String code) {
        String redisKey = BUSINIESS_PREFIX + code;
        String val = "";
        if (ObjectUtil.isEmpty(redisUtil.get(redisKey))) {
            WmsBusiniessParamConfig config = this.getOne(new LambdaQueryWrapper<WmsBusiniessParamConfig>().eq(WmsBusiniessParamConfig::getCode, code));
            if (ObjectUtil.isEmpty(config)) {
                throw new JeecgBootException("当前业务参数编码【" + code + "】未配置，请联系管理员配置");
            }
            val = config.getVal();
            redisUtil.set(redisKey, val);
        } else {
            val = (String) redisUtil.get(redisKey);
        }
        return val;
    }
}
